<!-- //#region Template -->
<template>
  <div class="makestep-page">
    <!-- 查询条件区域：按产品、版本、状态筛选 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" label-width="90px" @submit.prevent>
        <el-row :gutter="16">
          <el-col :xs="24" :sm="8">
            <el-form-item label="产品名称">
              <el-select v-model="searchForm.goodsname" placeholder="请选择产品" clearable filterable>
                <el-option v-for="item in goodsOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="8">
            <el-form-item label="版本号">
              <el-select v-model="searchForm.version" placeholder="请选择版本" clearable filterable>
                <el-option v-for="item in versionOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="8">
            <el-form-item label="启用状态">
              <el-select v-model="searchForm.isUse" placeholder="请选择状态" clearable>
                <el-option v-for="item in statusOptions" :key="item.value?.toString()" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row justify="end">
          <el-space>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-space>
        </el-row>
      </el-form>
    </el-card>

    <!-- 列表区域：展示成品工序 -->
    <el-card class="table-card" shadow="never">
      <div class="table-toolbar">
        <div class="title">成品工艺工序</div>
        <div class="actions">
          <el-button type="primary" @click="handleAdd">新增工序</el-button>
          <el-tag type="info" effect="light">共 {{ page.Totalcount }} 条</el-tag>
        </div>
      </div>

      <el-table :data="tableData" border height="520" class="makestep-table">
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column prop="processname" label="工序名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="processcode" label="工序编号" width="130" align="center" />
        <el-table-column prop="goodsname" label="产品名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="version" label="版本" width="100" align="center" />
        <el-table-column prop="deliverables" label="产出物" min-width="140" show-overflow-tooltip />
        <el-table-column prop="kahuna" label="负责人" width="100" align="center" />
        <el-table-column prop="departmentname" label="所属部门" width="130" align="center" />
        <el-table-column prop="spanTime" label="工序时长(min)" width="130" align="center" />
        <el-table-column label="启用状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isUse ? 'success' : 'info'">{{ row.isUse ? '启用' : '禁用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220" align="center">
          <template #default="{ row }">
            <el-space>
              <el-button type="primary" link @click="handleView(row)">详情</el-button>
              <el-button type="warning" link @click="handleToggle(row)">{{ row.isUse ? '禁用' : '启用' }}</el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="page.Pageindex"
          v-model:page-size="page.Pagesize"
          :total="page.Totalcount"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          background
        />
      </div>
    </el-card>

    <!-- 新增工序弹窗 -->
    <el-dialog v-model="dialogVisible" title="新增工序" width="640px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="110px">
        <el-form-item label="工序名称" prop="processname">
          <el-input v-model="formData.processname" placeholder="请输入工序名称" />
        </el-form-item>
        <el-form-item label="工序编号" prop="processcode">
          <el-input v-model="formData.processcode" placeholder="例如 OP10" />
        </el-form-item>
        <el-form-item label="工序描述" prop="processdescription">
          <el-input type="textarea" v-model="formData.processdescription" :rows="2" placeholder="请输入工序描述" />
        </el-form-item>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="goodsname">
              <el-input v-model="formData.goodsname" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本号" prop="version">
              <el-input v-model="formData.version" placeholder="例如 1.0V" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="负责人" prop="kahuna">
              <el-input v-model="formData.kahuna" placeholder="请输入负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="departmentname">
              <el-input v-model="formData.departmentname" placeholder="请输入部门" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
        <el-form-item label="工序时长" prop="spanTime">
          <el-input-number v-model="formData.spanTime" :min="0" :max="1000" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备编号" prop="equipmentId">
              <el-input-number v-model="formData.equipmentId" :min="1" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="产出物" prop="deliverables">
          <el-input v-model="formData.deliverables" placeholder="请输入产出物" />
        </el-form-item>
        <el-form-item label="启用状态" prop="isUse">
          <el-switch v-model="formData.isUse" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<!-- //#endregion Template -->

<script setup lang="ts">

//#region Imports
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import myaxios from '@/Http/http'
import { useCounterStore } from '@/stores/counter'
//#endregion

//#region Store & Router
const router = useRouter()
const store = useCounterStore()
//#endregion

//#region 列表及筛选选项
const tableData = ref<MakestepItem[]>([])
const goodsOptions = ref<string[]>([])
const versionOptions = ref<string[]>([])
const statusOptions = [
  { label: '全部', value: '' },
  { label: '启用', value: true },
  { label: '禁用', value: false }
]
//#endregion

//#region 当前操作人
// 当前操作人，优先取真实姓名，其次用户名，最后回退“系统”
const currentUserName = computed(() => store.userinfo.realname || store.userinfo.username || '系统')
//#endregion

//#region 分页与查询表单
const page = reactive({
  Pageindex: 1,
  Pagesize: 10,
  Totalcount: 0
})

const searchForm = reactive({
  goodsname: '',
  version: '',
  isUse: '' as '' | boolean
})

const formRef = ref<FormInstance>()
const dialogVisible = ref(false)
const submitLoading = ref(false)
//#endregion

//#region 表单模型
const formData = reactive({
  processname: '',
  processcode: '',
  processdescription: '',
  version: '1.0V',
  goodsname: '',
  deliverables: '',
  kahuna: '',
  departmentname: '',
  isUse: true,
  spanTime: 10,
  equipmentId: 1
})
//#endregion

//#region 类型定义
type MakestepItem = {
  id: number
  processname: string
  processcode: string
  processdescription: string
  version: string
  goodsname: string
  deliverables: string
  kahuna: string
  departmentname: string
  isUse: boolean
  spanTime: number
  equipmentId: number
}
//#endregion

//#region 表单校验
const formRules: FormRules = {
  processname: [{ required: true, message: '请输入工序名称', trigger: 'blur' }],
  processcode: [{ required: true, message: '请输入工序编号', trigger: 'blur' }],
  goodsname: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
  spanTime: [{ required: true, message: '请输入工序时长', trigger: 'change' }]
}
//#endregion

//#region 下拉加载
// 加载产品与版本下拉，供筛选和新增弹窗共用
const loadOptions = async () => {
  try {
    const res = await myaxios.get('/api/Makesteps/GetProductSelectOptions')
    if (res.data.code === 200) {
      goodsOptions.value = res.data.result?.goodsOptions ?? []
      versionOptions.value = res.data.result?.versionOptions ?? []
    }
  } catch (error) {
    console.error('获取下拉选项失败', error)
  }
}
//#endregion

//#region 查询与筛选
// 查询工序主列表
const loadData = async () => {
  try {
    const res = await myaxios.get('/api/Makesteps/GetProductMakestepList', {
      params: {
        Pageindex: page.Pageindex,
        Pagesize: page.Pagesize,
        Goodsname: searchForm.goodsname || undefined,
        Version: searchForm.version || undefined,
        IsUse: searchForm.isUse === '' ? undefined : searchForm.isUse
      }
    })
    tableData.value = res.data.listResult ?? []
    page.Totalcount = res.data.totalcount ?? 0
  } catch (error) {
    console.error('获取工序列表失败', error)
    tableData.value = []
    page.Totalcount = 0
  }
}

// 点击查询按钮
const handleSearch = () => {
  page.Pageindex = 1
  loadData()
}

// 重置筛选条件
const handleReset = () => {
  searchForm.goodsname = ''
  searchForm.version = ''
  searchForm.isUse = ''
  page.Pageindex = 1
  loadData()
}
//#endregion

//#region 监听
// 分页或页大小变化时重新拉取列表
watch(
  () => [page.Pageindex, page.Pagesize],
  () => {
    loadData()
  }
)
//#endregion

//#region 新增弹窗
// 打开新增弹窗
const handleAdd = () => {
  dialogVisible.value = true
  resetForm()
}

// 重置表单字段
const resetForm = () => {
  formData.processname = ''
  formData.processcode = ''
  formData.processdescription = ''
  formData.version = 'V1.0'
  formData.goodsname = ''
  formData.deliverables = ''
  formData.kahuna = ''
  formData.departmentname = ''
  formData.isUse = true
  formData.spanTime = 10
  formData.equipmentId = 1
  formRef.value?.clearValidate()
}
//#endregion

//#region 新增工序
// 提交新增请求（使用 Pinia 中的操作人）
const handleSubmit = () => {
  if (!formRef.value) return
  formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      const res = await myaxios.post('/api/Makesteps/CreateProductMakestep', {
        processname: formData.processname,
        processcode: formData.processcode,
        processdescription: formData.processdescription,
        version: formData.version,
        goodsname: formData.goodsname,
        deliverables: formData.deliverables,
        kahuna: formData.kahuna,
        departmentname: formData.departmentname,
        isUse: formData.isUse,
        spanTime: formData.spanTime,
        equipmentId: formData.equipmentId,
        currentUserName: currentUserName.value
      })
      if (res.data.code === 200) {
        ElMessage.success(res.data.message || '新增成功')
        dialogVisible.value = false
        loadOptions()
        loadData()
      } else {
        ElMessage.error(res.data.message || '新增失败')
      }
    } catch (error: any) {
      ElMessage.error(error.response?.data?.message || '新增失败')
    } finally {
      submitLoading.value = false
    }
  })
}

// 启用/禁用操作
const handleToggle = (row: MakestepItem) => {
  const target = !row.isUse
  ElMessageBox.confirm(`确定要${target ? '启用' : '禁用'}工序「${row.processname}」吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: target ? 'info' : 'warning'
  })
    .then(async () => {
      try {
        const res = await myaxios.put('/api/Makesteps/ToggleProductMakestep', {
          id: row.id,
          isUse: target,
          currentUserName: currentUserName.value
        })
        if (res.data.code === 200) {
          ElMessage.success(res.data.message || '操作成功')
          loadData()
        } else {
          ElMessage.error(res.data.message || '操作失败')
        }
      } catch (error: any) {
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    })
    .catch(() => {})
}
//#endregion

//#region 路由跳转
// 详情跳转
const handleView = (row: MakestepItem) => {
  router.push({
    path: '/MakestepdetailsView',
    query: { id: row.id }
  })
}
//#endregion

//#region 生命周期
// 进入页面即加载下拉+数据
onMounted(() => {
  loadOptions()
  loadData()
})
//#endregion
</script>

<!-- //#region Style -->
<style scoped>
.makestep-page {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.table-toolbar .title {
  font-size: 16px;
  font-weight: 600;
}

.actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding-top: 12px;
}

.makestep-table :deep(.el-table__body-wrapper) {
  min-height: 360px;
}
</style>
<!-- //#endregion Style -->